/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.config;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.lang.Nullable;
import org.springframework.util.StringValueResolver;

/**
 * 注释描述很长,但是很有用途!!!
 * <p>
 * 在Bean定义属性值中用于解析占位符的属性资源配置类的抽象基类,实现了从资源文件或者其他的配置文件中取出属性值放到bean定义中的功能.
 * 默认的占位符遵循Ant/log4J/JSP EL表达式的风格:
 * 比如,${属性名称}.
 * 或者在XML文件中定义属性:
 * <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 * <property name="driverClassName" value="${driver}"></property>
 * <property name="url" value="${dbname}"></property>
 * </bean>
 * 其对应的Properties属性文件大概是这样的:
 * dbname=mysql:mydb
 * <p>
 * 不过象这种配置,现在可以通过注解的形式来实现,比如:@Value("${属性配置名称}")
 * 这种配置的方式能够检查bean中引用的简单属性值.比如:List,Map,属性,以及Bean名称.
 * 而且属性值还可以引用其他配置,比如:
 * rootDir=myRootDir
 * subDir=${rootDir}/subDir
 * 和PropertyOverrideConfigurer不同的是,这种类型的子类允许在Bean定义中显示填充占位符.
 * 如果配置不能够解析占位符,就会抛出一个BeanDefinitionStoreException,如果你想要检查多个属性文件,
 * 可以通过setLocations方法来指定多个资源,同时,也可以指定多个配置器,每个配置器都有自己的占位符语法.
 * 如果无法解析占位符的,还可以通过使用ignoreUnresolvablePlaceholders来显示的禁止引发异常.
 * 可以通过setProperties方法为每个配置实例定义全局的属性值,或者使用默认值默认分隔符来设置默认值,默认分隔符为":",
 * 用户也可以通过setValueSeparator方法来自定义分隔符.
 * 比如: <property name="url" value="jdbc:${dbname:defaultdb}"/>
 * <p>
 * <p>
 * <p>
 * Abstract base class for property resource configurers that resolve placeholders
 * in bean definition property values. Implementations <em>pull</em> values from a
 * properties file or other {@linkplain org.springframework.core.env.PropertySource
 * property source} into bean definitions.
 * <p>
 * <p>The default placeholder syntax follows the Ant / Log4J / JSP EL style:
 * <p>
 * <pre class="code">${...}</pre>
 * <p>
 * Example XML bean definition:
 * <p>
 * <pre class="code">
 * <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"/>
 * <property name="driverClassName" value="${driver}"/>
 * <property name="url" value="jdbc:${dbname}"/>
 * </bean>
 * </pre>
 * <p>
 * Example properties file:
 * <p>
 * <pre class="code">driver=com.mysql.jdbc.Driver
 * dbname=mysql:mydb</pre>
 * <p>
 * Annotated bean definitions may take advantage of property replacement using
 * the {@link org.springframework.beans.factory.annotation.Value @Value} annotation:
 * <p>
 * <pre class="code">@Value("${person.age}")</pre>
 * <p>
 * Implementations check simple property values, lists, maps, props, and bean names
 * in bean references. Furthermore, placeholder values can also cross-reference
 * other placeholders, like:
 * <p>
 * <pre class="code">rootPath=myrootdir
 * subPath=${rootPath}/subdir</pre>
 * <p>
 * In contrast to {@link PropertyOverrideConfigurer}, subclasses of this type allow
 * filling in of explicit placeholders in bean definitions.
 * <p>
 * <p>If a configurer cannot resolve a placeholder, a {@link BeanDefinitionStoreException}
 * will be thrown. If you want to check against multiple properties files, specify multiple
 * resources via the {@link #setLocations locations} property. You can also define multiple
 * configurers, each with its <em>own</em> placeholder syntax. Use {@link
 * #ignoreUnresolvablePlaceholders} to intentionally suppress throwing an exception if a
 * placeholder cannot be resolved.
 * <p>
 * <p>Default property values can be defined globally for each configurer instance
 * via the {@link #setProperties properties} property, or on a property-by-property basis
 * using the default value separator which is {@code ":"} by default and
 * customizable via {@link #setValueSeparator(String)}.
 * <p>
 * <p>Example XML property with default value:
 * <p>
 * <pre class="code">
 * <property name="url" value="jdbc:${dbname:defaultdb}"/>
 * </pre>
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @see PropertyPlaceholderConfigurer
 * @see org.springframework.context.support.PropertySourcesPlaceholderConfigurer
 * @since 3.1
 */
public abstract class PlaceholderConfigurerSupport extends PropertyResourceConfigurer
		implements BeanNameAware, BeanFactoryAware {

	/**
	 * 默认占位符前缀
	 * Default placeholder prefix: {@value}
	 */
	public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";

	/**
	 * 默认占位符后缀
	 * Default placeholder suffix: {@value}
	 */
	public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

	/**
	 * 默认占位符默认值分隔符
	 * Default value separator: {@value}
	 */
	public static final String DEFAULT_VALUE_SEPARATOR = ":";


	/**
	 * 设置默认占位符前缀为DEFAULT_PLACEHOLDER_PREFIX
	 * Defaults to {@value #DEFAULT_PLACEHOLDER_PREFIX}
	 */
	protected String placeholderPrefix = DEFAULT_PLACEHOLDER_PREFIX;

	/**
	 * 设置默认占位符后缀为DEFAULT_PLACEHOLDER_SUFFIX
	 * Defaults to {@value #DEFAULT_PLACEHOLDER_SUFFIX}
	 */
	protected String placeholderSuffix = DEFAULT_PLACEHOLDER_SUFFIX;

	/**
	 * 设置默认占位符默认值分隔符为DEFAULT_VALUE_SEPARATOR
	 * Defaults to {@value #DEFAULT_VALUE_SEPARATOR}
	 */
	@Nullable
	protected String valueSeparator = DEFAULT_VALUE_SEPARATOR;
	/**
	 * 指定在真正使用解析出来的值之前是否取出属性值两端的空白.
	 */
	protected boolean trimValues = false;

	@Nullable
	protected String nullValue;
	/**
	 * 在遇到不能够解析的占位符时,是否忽略.
	 */
	protected boolean ignoreUnresolvablePlaceholders = false;
	/**
	 * Bean名称
	 */
	@Nullable
	private String beanName;
	/**
	 * Bean工厂
	 */
	@Nullable
	private BeanFactory beanFactory;


	/**
	 * 设置占位符前缀
	 * Set the prefix that a placeholder string starts with.
	 * The default is {@value #DEFAULT_PLACEHOLDER_PREFIX}.
	 */
	public void setPlaceholderPrefix(String placeholderPrefix) {
		this.placeholderPrefix = placeholderPrefix;
	}

	/**
	 * 设置占位符后缀
	 * Set the suffix that a placeholder string ends with.
	 * The default is {@value #DEFAULT_PLACEHOLDER_SUFFIX}.
	 */
	public void setPlaceholderSuffix(String placeholderSuffix) {
		this.placeholderSuffix = placeholderSuffix;
	}

	/**
	 * 指定占位符默认值分隔符,如果不想应用默认值分隔符可以将其设置为null.
	 * Specify the separating character between the placeholder variable
	 * and the associated default value, or {@code null} if no such
	 * special character should be processed as a value separator.
	 * The default is {@value #DEFAULT_VALUE_SEPARATOR}.
	 */
	public void setValueSeparator(@Nullable String valueSeparator) {
		this.valueSeparator = valueSeparator;
	}

	/**
	 * 指定在真正使用解析出来的值之前是否取出属性值两端的空白,默认为false.
	 * Specify whether to trim resolved values before applying them,
	 * removing superfluous whitespace from the beginning and end.
	 * <p>Default is {@code false}.
	 *
	 * @since 4.3
	 */
	public void setTrimValues(boolean trimValues) {
		this.trimValues = trimValues;
	}

	/**
	 * 设置一个默认值,用来再解析的时候处理null,比如空字符串或者字符串null.
	 * 不过需要注意的是,这种只会应用在完整的属性值中,即属性本身完全由占位符构成,而不会应用在拼接的属性值中.
	 * 在默认的场景下,不会定义这样的空值,也就是说除非我们明确的在这里设置相应的值,否则不会有值来替代null.
	 * <p>
	 * <p>
	 * Set a value that should be treated as {@code null} when resolved
	 * as a placeholder value: e.g. "" (empty String) or "null".
	 * <p>Note that this will only apply to full property values,
	 * not to parts of concatenated values.
	 * <p>By default, no such null value is defined. This means that
	 * there is no way to express {@code null} as a property value
	 * unless you explicitly map a corresponding value here.
	 */
	public void setNullValue(String nullValue) {
		this.nullValue = nullValue;
	}

	/**
	 * 设置是否忽略不可解析的占位符.
	 * 默认值为false:当解析占位符失败的时候会抛出异常.将该开关设置为true,可以在这种场景下,保留该占位符,并交给其他的占位符解析器来处理.
	 * <p>
	 * <p>
	 * Set whether to ignore unresolvable placeholders.
	 * <p>Default is "false": An exception will be thrown if a placeholder fails
	 * to resolve. Switch this flag to "true" in order to preserve the placeholder
	 * String as-is in such a case, leaving it up to other placeholder configurers
	 * to resolve it.
	 */
	public void setIgnoreUnresolvablePlaceholders(boolean ignoreUnresolvablePlaceholders) {
		this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
	}

	/**
	 * 我们只需要检查是否解析我们自己的bean定义,为了避免在本地资源文件中解析失败.
	 * 后一种情况可能会发生在系统资源占位符里.
	 * <p>
	 * <p>
	 * Only necessary to check that we're not parsing our own bean definition,
	 * to avoid failing on unresolvable placeholders in properties file locations.
	 * The latter case can happen with placeholders for system properties in
	 * resource locations.
	 *
	 * @see #setLocations
	 * @see org.springframework.core.io.ResourceEditor
	 */
	@Override
	public void setBeanName(String beanName) {
		this.beanName = beanName;
	}

	/**
	 * 只需要检查是不是要解析我们自己的bean定义,来避免本地资源文件中不能解析的占位符.
	 * 后裔中情况可能会发生在系统资源占位符里.
	 * Only necessary to check that we're not parsing our own bean definition,
	 * to avoid failing on unresolvable placeholders in properties file locations.
	 * The latter case can happen with placeholders for system properties in
	 * resource locations.
	 *
	 * @see #setLocations
	 * @see org.springframework.core.io.ResourceEditor
	 */
	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

	/**
	 * 解析属性(占位符)
	 *
	 * @param beanFactoryToProcess
	 * @param valueResolver
	 */
	protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
									   StringValueResolver valueResolver) {
		//Bean定义解析访问者,标准的访问者应用
		BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);
		//获取Bean定义名称集合
		String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
		for (String curName : beanNames) {
			//避免在属性文件位置发生无法解析的占位符,检查是否解析我们自己的Bean定义.
			// Check that we're not parsing our own bean definition,
			// to avoid failing on unresolvable placeholders in properties file locations.

			if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
				//获取Bean定义,通过访问者模式,替换属性,会在内部,直接修改引用的值.
				BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(curName);
				try {
					visitor.visitBeanDefinition(bd);
				} catch (Exception ex) {
					throw new BeanDefinitionStoreException(bd.getResourceDescription(), curName, ex.getMessage(), ex);
				}
			}
		}
		//Spring2.5的新功能:解析别名和别名中的占位符.
		// New in Spring 2.5: resolve placeholders in alias target names and aliases as well.
		beanFactoryToProcess.resolveAliases(valueResolver);
		//spring3.0中,解析嵌入值的占位符,比如注解中的值
		// New in Spring 3.0: resolve placeholders in embedded values such as annotation attributes.
		beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);
	}

}
